<template>
    <!-- 主体 -->
    <div class="broker-bg">
        <!-- 按钮 -->
        <div class="broker-head">
            <!-- 输入框与新增食品 -->
            <div>
                <el-input v-model="userInput" type="number" placeholder="请输入溯源码" clearable />
                <el-button type="primary" class="elbutton" @click="openAddFood(userInput)">新增食品</el-button>
            </div>
            <!-- 退出登录 -->
            <el-button type="danger" class="elbutton" @click="LoginOut">退出登录</el-button>
        </div>
        <!-- 主体 -->
        <div class="broker-cont">
            <!-- 数据表格 -->
            <div class="broker-table">
                <el-table :data="showData" style="width: 100%;" size="large" class="broker-table-cont"
                    @sort-change="changeSort">
                    <!-- 11111111 -->
                    <el-table-column prop="traceNumber" header-align="center" align="center" sortable="custom"
                        label="溯源码">
                        <template #default="showData">
                            <el-popover :effect="dkm.lightMode ? 'light' : 'dark'" placement="right"
                                popper-class="broker-table-popover" trigger="click">
                                <template #reference>
                                    <p class="broker-table-label">{{ showData.row.traceNumber }}</p>
                                </template>
                                <template #default>
                                    <div class="broker-table-bg">
                                        <div class="broker-table-p">
                                            <p>食品基本信息</p>
                                        </div>
                                        <div class="broker-table-table">
                                            <div v-for="(item, index) in sortFoodATTR(showData.row)" :key="index">
                                                <div>
                                                    <div>{{ index }}</div>
                                                </div>
                                                <div>
                                                    <div>{{ item }}</div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </template>
                            </el-popover></template>
                    </el-table-column>
                    <!-- 11111111 -->
                    <el-table-column prop="name" header-align="center" align="center" label="食品名称" />
                    <el-table-column prop="timestamp" header-align="center" align="center" sortable="custom"
                        label="上架时间" />
                    <el-table-column prop="quality" header-align="center" align="center" label="质检情况" />
                    <el-table-column prop="from_address" header-align="center" align="center" label="发货单位" />
                    <el-table-column prop="to_address" header-align="center" align="center" label="收货单位" />
                </el-table>
            </div>
            <!-- 分页 -->
            <div class="broker-page">
                <el-pagination v-model:page-size="page_size" v-model:current-page="now_page" :page-sizes="sizes"
                    :default-page-size="sizes[0]" :background="false"
                    layout="total, sizes, prev, pager, next, jumper,slot" :total="brokerLength">
                </el-pagination>
            </div>
        </div>
    </div>

    <!-- 新增食品弹出框 -->
    <el-dialog v-model="addFoodFlag" class="borkerDialog" title="新增食品" width="auto" align-center center>
        <el-form :model="newFood">
            <!-- 质检情况 -->
            <el-form-item ref="formItemRef1" label="质检情况" prop="quality" :rules="{ required: true, message: '请选择质检情况' }"
                required label-width="150px" label-position="left">
                <el-radio-group v-model="newFood.quality">
                    <el-radio value="1">优质</el-radio>
                    <el-radio value="2">合格</el-radio>
                    <el-radio value="3">不合格</el-radio>
                </el-radio-group>
            </el-form-item>
            <!-- 收货单位 -->
            <el-form-item ref="formItemRef2" label="收货单位(本单位)" prop="take"
                :rules="{ required: true, message: '请输入收货单位' }" label-width="150px" label-position="left">
                <el-input disabled v-model.number="newFood.take" />
            </el-form-item>
            <!-- 按钮 -->
            <div class="dialog-botton">
                <el-button @click="clearAddFood">取消</el-button>
                <el-button type="primary" @click="ensureAddFood">
                    确定
                </el-button>
            </div>
            <!-- 分割线 -->
            <el-divider />
            <!-- 商品信息 -->
            <div class="dialog-message-bg">
                <div class="dialog-message-p">
                    <p>以下是溯源码为{{ userInput }}的溯源信息</p>
                    <p>食品基本信息</p>
                </div>
                <div v-for="(item, index) in foodMess" :key="index" class="dialog-message-table">
                    <div>
                        <div>{{ index }}</div>
                    </div>
                    <div>
                        <div>{{ item }}</div>
                    </div>
                </div>
            </div>
        </el-form>
    </el-dialog>
</template>

<script setup lang='js' name=''>
import { ref, computed } from 'vue'
import strToTime from '@/utils/strToTime';
import showMessage from '@/utils/showMessage';
import { LoginOut } from '@/hooks/useLoginOut';
import { CheckInput } from '@/hooks/userCheckInput';
import { userDataStore } from '@/store/useUserDataStore';
import getDistributingAPI from '@/API/main/Broker/distributing';
import getAdddistributionAPI from '@/API/main/Broker/adddistribution';
import getTraceAPI from '@/API/main/trace';
const dkm = userDataStore()

// -----数据表格-----
// 数据表格数据
const brokerData = ref([])
// 条目数
const brokerLength = ref(0)
// 每次展示多少数据
const sizes = ref([10, 20, 50, 100])
// 当前每页展示条目
const page_size = ref(10)
// 当前页数
const now_page = ref(1)
// 载入食品
async function getDistributing() {
    const res = await getDistributingAPI()
    if (res) {
        brokerData.value = res.data
        showMessage("加载成功", "success")
        // console.log(brokerData.value)
        brokerLength.value = brokerData.value.length

    }
}
getDistributing()

const sortRule = ref("")
const sortName = ref("")
// 源数据排序
const sortData = computed(() => {

    if (brokerData.value) {
        // console.log(sortName.value)
        if (sortRule.value == 1) {
            return brokerData.value.toSorted((a, b) => {
                return a[sortName.value] - b[sortName.value]
            })
        } else if (sortRule.value == 2) {
            return brokerData.value.toSorted((a, b) => {
                return b[sortName.value] - a[sortName.value]
            })
        } else {
            return brokerData.value
        }
    } else { return null }
})
// 实际展示数据
const showData = computed(() => {
    let vardata = ref(JSON.parse(JSON.stringify(sortData.value)).slice((now_page.value - 1) * page_size.value, now_page.value * page_size.value))
    vardata.value.forEach(element => {
        element["quality"] = element["quality"] == 1 ? "优质" : element["quality"] == 2 ? "合格" : "不合格"
        element["produce_time"] = strToTime(parseInt(element["produce_time"]))
        element["timestamp"] = strToTime(parseInt(element["timestamp"]), "Ciallo")
    })
    return vardata.value
})
// 排序函数
function changeSort(e) {
    switch (e.order) {
        case "ascending": sortRule.value = 1; break;
        case "descending": sortRule.value = 2; break;
        default: sortRule.value = null; break;
    }
    if (e.order) {
        sortName.value = e.prop
    } else {
        sortName.value = null
    }
}

function sortFoodATTR(attr) {
    const foodDictionary = {
        "溯源码:": attr.traceNumber,
        "食品名称:": attr.name,
        "生产商:": attr.from,
        "生产商地址:": attr.from_address,
        "生产时间": attr.produce_time
    }
    return foodDictionary
}



// -----添加食品-----
const userInput = ref()
// 弹出框开关
const addFoodFlag = ref(false)
// 新增食品表格
const newFood = ref({
    code: userInput.value,
    quality: "",
    take: JSON.parse(localStorage.getItem("SLuserData"))?JSON.parse(localStorage.getItem("SLuserData"))["username"]:null
})

// 添加基本信息框架
const foodMess = ref({
    "溯源码": userInput,
    "食品名称": "正在加载......",
    "生产商": "正在加载......",
    "生产商地址": "正在加载......",
    "生产时间": "正在加载......"
})
// 输入框验证规则
const formItemRef1 = ref()
const formItemRef2 = ref()

async function openAddFood(value) {
    if (CheckInput(value, "请输入溯源码")) {
        // console.log(value)
        addFoodFlag.value = true
        const res = await getTraceAPI(value)
        // console.log(res)
        if (res) {
            foodMess.value.食品名称 = res.data[0].name
            foodMess.value.生产时间 = strToTime(res.data[0].produce_time)
            foodMess.value.生产商 = res.data[0].from
            foodMess.value.生产商地址 = res.data[0].from_address
        } else {
            showMessage("加载失败,请核实该溯源码是否存在")
        }
    }
}
function clearAddFood() {
    // 重置输入框
    userInput.value = ""
    newFood.code = ""
    newFood.quality = ""
    newFood.take = ""
    // 关闭页面
    addFoodFlag.value = false
    // 刷新验证
    formItemRef1.value.resetField();
    formItemRef2.value.resetField();
    // 重置基本信息
    foodMess.value.生产商地址 = "正在加载......"
    foodMess.value.生产商 = "正在加载......"
    foodMess.value.生产时间 = "正在加载......"
    foodMess.value.食品名称 = "正在加载......"
}
function ensureAddFood() {
    const promises = [
        formItemRef1.value.validate(),
        formItemRef2.value.validate(),
    ];
    Promise.all(promises)
        .then(() => {
            // console.log("ciallo")
            async function getAdddistribution(traceNumber, traceName, quality) {
                const res = await getAdddistributionAPI(traceNumber, traceName, quality)
                // console.log(res.data.msg)
                if (res.data.ret) {
                    showMessage(res.data.msg, "success")
                    getDistributing()
                } else {
                    showMessage(res.data.msg)
                }
            }
            getAdddistribution(userInput.value, JSON.parse(localStorage.getItem("SLuserData"))["username"], newFood.value.quality)
            clearAddFood()
        })
        .catch((errors) => {
        });
}
</script>

<style scoped>
/* 主体框架 */
.broker-bg {
    width: 100%;
    height: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

/* 顶部按钮 */
.broker-head {
    display: flex;
    justify-content: space-between;
}

.broker-head>div {
    display: flex;
    gap: 10px;
}

.broker-head .el-input {
    width: 300px;
    height: 45px;
}

.elbutton {
    width: 100px;
    height: 45px;
}

/* 主体 */
.broker-cont {
    width: 100%;
    height: 100%;
    margin-top: 20px;
    gap: 10px;
    display: flex;
    flex-direction: column;
    align-items: center;
}

/* -----数据表格----- */
.broker-table {
    width: 100%;
    height: calc(100% - 110px);
    flex: 1;
}

.broker-table-cont {
    height: 100%;
    background: var(--Main_tableBG2);
    transition: all 0.5s;
}


/* -----分页----- */
.broker-page {
    height: 50px;
    flex: 1;
}

/* -----新增食品弹出框----- */
/* 主体 */
.el-dialog .el-form {
    width: 500px;
    padding: 20px;
    padding-bottom: 0;
    margin-bottom: -20px;
}

/* 质检情况 */
.el-dialog .el-radio-group {
    width: 100%;
    display: flex;
    justify-content: space-around;
}

/* 收货单位输入框 */
.el-dialog .el-input {
    width: 100%;
}

/* 按钮 */
.dialog-botton {
    display: flex;
    justify-content: space-between;
}

.dialog-botton .el-button {
    width: 30%;
    height: 40px;
}

/* 信息展示框 */
.dialog-message-bg {
    width: 100%;
    display: flex;
    flex-direction: column;
}

.dialog-message-p>p:nth-child(1) {
    color: green;
    font-size: 20px;
    font-weight: bold;

}

.dialog-message-p>p:nth-child(2) {
    color: black;
    font-size: 15px;
    font-weight: bold;
    text-align: center;
    margin: 10px;
    color: var(--Main_TextColor1);
}

.dialog-message-table {
    width: 100%;
    display: grid;
    gap: 10px;
    grid-template-columns: 1fr 1fr;
    margin-bottom: 20px;
}

.dialog-message-table>div {
    display: flex;
    flex-direction: column;
    justify-content: center;
}

.dialog-message-table>div>div {
    display: block;
    word-break: break-word;
    text-align: center;
}
</style>
<style>
.broker-table-popover {
    width: 300px !important;
}

.broker-table-bg {
    width: 100%;
}

.broker-table-label {
    color: blue;
    cursor: pointer;
}

.broker-table-p {
    font-size: 16px;
    font-weight: bold;
    text-align: center;
    margin-bottom: 20px;
}

.broker-table-table {
    width: 100%;
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.broker-table-table>div {
    display: grid;
    grid-template-columns: 1fr 1fr;
    align-items: center;
}


.broker-table-table>div>div>div {
    width: 100%;
    display: block;
    word-break: break-word;
    text-align: center;
}
</style>
<style>
.borkerDialog {
    background: var(--Dialog_bg1);
    color: white;
}

.borkerDialog .el-input *,
.borkerDialog>*>* {
    color: var(--Dialog_color);
}
</style>